<!DOCTYPE html>
<html lane="zh-cn">
<head>
	<title>pane</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
	<!-- <link rel="stylesheet" href="../static/css/bootstrap.css"> -->
	<link rel="stylesheet" href="../static/css/pane.css">
	<link rel="stylesheet" href="../static/css/flick/jquery-ui-1.8.23.custom.css">
	<link type="text/css" rel="stylesheet" href="../static/css/layout-default-latest.css" />

	<script type="text/javascript" src="../static/js/raphael-min.js"></script>
	<!-- <script type="text/javascript" src="../static/js/bootstrap.js"></script> -->
	<script type="text/javascript" src="../static/js/jquery.js"></script>
	<script type="text/javascript" src="../static/js/jquery-ui-1.8.23.custom.min.js"></script>
	<script type="text/javascript" src="../static/js/jquery.layout-latest.js"></script>
	<script type="text/javascript" src="../static/js/jquery.mousewheel.js"></script>
	<script type="text/javascript" src="../static/js/scale.raphael.js"></script>

</head>
<body>
	<div id="container">
		<div id="pane_wrapper" class="ui-layout-center">
			<div id="pane"></div>
			<div id="toolbar">
				<div class="demo">
				<ul id="toolbar">
					<li>
						<a id="rerun"><img src="../static/img/pencil_24.png" alt=""></a>
					</li>
					<li>
						<a id="select" class="dropbutton"><img src="../static/img/rect_24.png" alt=""></a>
						<ul class="dropdown">
							<li>
								<a><img src="../static/img/rect_filled_24.png" alt=""></a>
							</li>
							<li>
								<a><img src="../static/img/oneway_arrow_24.png" alt=""></a>
							</li>
						</ul>
					</li>
					<li>
						<a id="scale"><img src="../static/img/line_24.png" alt=""></a>
					</li>
				</ul>
				</div><!-- End demo -->
			</div>
		</div>
		<div id="material_folder" class="ui-layout-east">
			<div><p>素材夹</p></div>
		</div>
	</div>
	<div id="footer"></div>

	<script type="text/javascript">
		$(document).ready(function () {
			$('#container').layout({
				spacing_open: 0
			});
		

		var pane = document.getElementById("pane");
		var p = Raphael(pane);
		var paneOffset = $(pane).offset();
		var state = 0;
		var sketches = p.set();
		var toolbar = p.set();
		var material_folder = document.getElementById('material_folder');
		var pwidth = $(pane).width();
		var pheight = $(pane).height();
		var vleft = 5*pwidth;
		var vtop = 5*pheight;
		var vwidth = 5*pwidth;
		var vheight = 5*pheight;
		p.setViewBox(vleft, vtop, vwidth, vheight);
		// var bg = p.rect(0,0,11*pwidth,11*pheight).attr("fill","#FFF");

		var s = new WebSocket("ws://"+window.location.host+"/socket/{{ sessionid }}");
		// var s = new WebSocket("ws://echo.websocket.org");

		s.onopen = function(e) {
			console.log("opened");
			// alert("opened");
		}
		s.onclose = function(e) {
			console.log("closed");
			// alert("closed");
		}

		s.onmessage = function(e) {
			console.log(e.data);
			message_handler(JSON.parse(e.data));
		}

		// bg.click(function(e){
		// 	p.circle(e.x,e.y,10);
		// })


		pane.onmousedown = mousedwon_handler;
		pane.onmousemove = mousemove_handler;
		pane.onmouseup = mouseup_handler;

		pane.addEventListener("touchstart", touchstart_handler);
		pane.addEventListener("touchmove", touchmove_handler);
		pane.addEventListener("touchend", touchend_handler);

		material_folder.addEventListener('dragover', dragOver_handler, false);
		material_folder.addEventListener('drop', fileSelected_handler, false);
		pane.addEventListener('dragover',dragOver_handler,false);
		pane.addEventListener("drop",paneDrop_handler,false);

		// var zoom = 1;

		function vx(x){
			return vleft+x/pwidth*vwidth;
		}

		function vy (y) {
			return vtop+y/pheight*vheight;
		}

		$(pane).bind('mousewheel', function(event, delta, deltaX, deltaY) {
			event.preventDefault();
			var rate = 0.1;
			var x = vx(event.offsetX);
			var y = vy(event.offsetY);
			console.log(x,y,pwidth,pheight,vleft,vtop,vwidth,vheight);
			vleft = x-(x-vleft)*(1+delta*rate/2);
			vtop = y-(y-vtop)*(1+delta*rate/2);
			vwidth *= 1+delta*rate/2;
			vheight *= 1+delta*rate/2;
			p.setViewBox(vleft,vtop,vwidth,vheight);


		});

		for (var i = 0; i <= 10; i++) {
			toolbar.push(p.rect(300+i*35,0,35,35,5))
		};
		toolbar.attr('fill','#fff')

		toolbar[0].click(function(){
			state = 0;
			sketches.undrag();
		})

		toolbar[1].click(function(){
			state = 2;
			sketches.undrag();
		})

		toolbar[2].click(function(){
			state = 4;
			sketches.drag(dragmove_handler,dragstart_handler,dragend_handler);
			sketches.hover(
				function(){
					if(state === 4)
					this.glowset = this.glow();
				},	
				function(){
					if(state === 4)
					this.glowset.remove();
			});
		});


		// bg.drag(sketch_move,sketch_start,sketch_end);

			
		toolbar.hover(function(){
			this.animate({
				fill: '#1669AD'
			}, 300);
		}, function(){
			this.animate({
				fill: '#fff'
			}, 300);
		}).click(function(){
			this.animate({
				fill: '#000'
			}, 300);
		})

		var pencil = p.path('M25.31,2.872l-3.384-2.127c-0.854-0.536-1.979-0.278-2.517,0.576l-1.334,2.123l6.474,4.066l1.335-2.122C26.42,4.533,26.164,3.407,25.31,2.872zM6.555,21.786l6.474,4.066L23.581,9.054l-6.477-4.067L6.555,21.786zM5.566,26.952l-0.143,3.819l3.379-1.787l3.14-1.658l-6.246-3.925L5.566,26.952z').attr('fill','#888').attr('stroke','#fff0').translate(300,0)

		function excute_send (command, param) {
			var message = {command:command, param:param};
			option[command](param);
			s.send(JSON.stringify(message));
		}

		function message_handler (message) {
			option[message.command](message.param);
		}

		function mousedwon_handler (e) {
			var param = {offsetX:vx(e.offsetX),offsetY:vy(e.offsetY)};
			var command = "";
			if(state === 0 || state === 2){
				if(state === 0){
					command = "sketch_start";
					state++;
				}
				if(state === 2){
					command = "rect_start";
					state++;
				}
				excute_send(command,param);
			}
		}

		function mousemove_handler (e) {
			var param = {offsetX:vx(e.offsetX),offsetY:vy(e.offsetY)};
			var command = "";
			if(state === 1 || state === 3){
				if(state === 1){
					command = "sketch_move";
				}
				if(state === 3){
					command = "rect_move";
				}
				excute_send(command,param);
			}
		}

		function mouseup_handler (e) {
			var param = {};
			var command = "";
			if(state === 1 || state === 3){
				if(state === 1){
					command = "sketch_end";
					state--;
				}
				if(state === 3){
					command = "rect_end";
					state--;
				}
			}
		}

		function touchstart_handler (e) {
			e.preventDefault();
			if (e.touches.item(0) == e.targetTouches.item(0)){
				var touch = e.touches[0];
				// alert(touch.pageX-offset.left)
				var param = {offsetX:touch.pageX-paneOffset.left, offsetY:touch.pageY-paneOffset.top};
				// alert(touch.pageX);
				var command = "";
				if(state === 0 || state === 2){
					if(state === 0){
						command = "sketch_start";
						state++;
					}
					if(state === 2){
						command = "rect_start";
						state++;
					}
					excute_send(command,param);
				}
			}
		}

		function touchmove_handler (e) {
			e.preventDefault();
			if (e.touches.item(0) == e.targetTouches.item(0)){
				var touch = e.touches[0];
				var param = {offsetX:touch.pageX-paneOffset.left, offsetY:touch.pageY-paneOffset.top};
				var command = "";
				if(state === 1 || state === 3){
					if(state === 1){
						command = "sketch_move";
					}
					if(state === 3){
						command = "rect_move";
					}
					excute_send(command,param);
				}
			}
		}

		function touchend_handler (e) {
			e.preventDefault();
			if (e.touches.item(0) == e.targetTouches.item(0)){
				var param = {};
				var command = "";
				if(state === 1 || state === 3){
					if(state === 1){
						command = "sketch_end";
						state--;
					}
					if(state === 3){
						command = "rect_end";
						state--;
					}
				}
			}
		}

		var option = new Array();

		option['sketch_start'] = function (param) {
			var newpath = p.path("M"+String(param.offsetX)+','+String(param.offsetY));
			newpath.attr('stroke-width', 5);
			newpath.attr('stroke-linecap', 'round');
			newpath.attr('stroke-linejoin', 'round');
			sketches.push(newpath)
		}

		option['sketch_move'] = function (param) {
			var pathnow = sketches[sketches.length-1]
				var newpathString = pathnow.attr('path')+"L"+String(param.offsetX)+','+String(param.offsetY);
				pathnow.attr('path',newpathString);
		}
		option['sketch_end'] = function (param) {
			
		}

		option['rect_start'] = function (param) {
			var newrect = p.rect(param.offsetX,param.offsetY,0,0);
			newrect.ox = param.offsetX;
			newrect.oy = param.offsetY;
			newrect.attr('stroke-width',5);
			sketches.push(newrect);
		}

		option['rect_move'] = function (param) {
			var newrect = sketches[sketches.length-1]
			var x = param.offsetX;
			var y = param.offsetY;
			if(x<newrect.ox){newrect.attr('x',x)};
			if(y<newrect.oy){newrect.attr('y',y)};
			newrect.attr('width',Math.abs(x-newrect.ox));
			newrect.attr('height',Math.abs(y-newrect.oy));
		}

		option['rect_end'] = function (param) {
			var newrect = sketches[sketches.length-1]
			newrect.attr('stroke-width',3);
		}

		option['insert_image'] = function (param) {
			var newpic = p.image(param.src,param.x,param.y,param.width,param.height);
			sketches.push(newpic);
		}

		option['drag_start'] = function (param) {
			var elem = p.getById(param.id);
			elem.glowset.remove();
			elem.ox = elem.attr('x');
			elem.oy = elem.attr('y');
		}

		option['drag_move'] = function (param) {
			var elem = p.getById(param.id);
			elem.attr('x',elem.ox+param.dx).attr('y',elem.oy+param.dy);
		}

		option['drag_end'] = function (param) {
			var elem = p.getById(param.id);
			elem.glowset = elem.glow();
		}

		function dragstart_handler (x,y,e) {
			state++;
			var command = 'drag_start';
			var param = {x:x,y:y,id:this.id};
			excute_send(command,param);
		}

		function dragmove_handler (dx,dy,x,y,e) {
			var command = 'drag_move';
			var param = {dx:dx,dy:dy,id:this.id};
			excute_send(command,param);
		}

		function dragend_handler (e){
			state--;
			var command = 'drag_end';
			var param = {id:this.id};
			excute_send(command,param);
		}

		function dragOver_handler (e) {
			e.stopPropagation();
			e.preventDefault();
			e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
		}

		function fileSelected_handler (e) {
			e.stopPropagation();
			e.preventDefault();
			var files = e.dataTransfer.files; // FileList object

		    // Loop through the FileList and render image files as thumbnails.
		    for (var i = 0, f; f = files[i]; i++) {

		      // Only process image files.
		      if (!f.type.match('image.*')) {
		        continue;
		      }

		      var reader = new FileReader();

		      // Closure to capture the file information.
		      reader.onload = (function(theFile) {
		        return function(e) {
		          // Render thumbnail.
		          var span = document.createElement('span');
		          // span.innerHTML = ['<img class="thumb" draggable="true" style="cursor: move;" src="', e.target.result,
		          //                   '" title="', escape(theFile.name), '"/>'].join('');
		          var img = new Image;
		          img.class = "thumb";
		          img.src = e.target.result;
		          span.appendChild(img);
		          img.addEventListener("dragstart",function(e){
		          	e.dataTransfer.setData('image/png',this.src);
		          	e.dataTransfer.setData('application/json',JSON.stringify({width:img.width,height:img.height}));
		          }, false);
		          document.getElementById('material_folder').insertBefore(span, null);
		        };
		      })(f);
		      // Read in the image file as a data URL.
		      reader.readAsDataURL(f);
		  }
		}
		

		function paneDrop_handler (e) {
			e.stopPropagation();
			e.preventDefault();
			var src = e.dataTransfer.getData("image/png");
			var hw = JSON.parse(e.dataTransfer.getData("application/json"));
			var img = new Image;
			param = {src:src,x:e.offsetX,y:e.offsetY,width:hw.width*4,height:hw.height*4};
			excute_send('insert_image',param);

		}
		$(function() {
				$( "#rerun" )
					.button()
					.click(function() {
						state = 0;
						sketches.undrag();
					})
				$("#scale").button().click(function(){
					sketches.forEach(function(el){
						el.scale(0.8,0.8,200,200);
					})
				})
				$("#select")
					.button( {
						// text: false,
						icons: {
							secondary:'ui-icon-triangle-1-s'
						}
					})
					.mousedown(function() {
						state = 2;
						sketches.undrag();
					})
					.parent().parent()
						.buttonset();
			});
	})

	</script>
</body>
</html>